package com.lancoo.znbkxx.teacher.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.Ext.Companion.COURSE_CLASSID
import com.lancoo.znbkxx.teacher.Ext.Companion.GLOBAL_GRADE_STU
import com.lancoo.znbkxx.teacher.Ext.Companion.SCHOOLID
import com.lancoo.znbkxx.teacher.Ext.Companion.STU_ID
import com.lancoo.znbkxx.teacher.Ext.Companion.STU_NAME
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.HomeWorkAdapter
import com.lancoo.znbkxx.teacher.adapter.SpacesItemDecoration
import com.lancoo.znbkxx.teacher.adapter.StuNameAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.AibkAnalysisAnswerSheetActivity_1v1
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.AibkPaperPreviewActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.AibkQuesMarkActivity
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtOnlinetutorBinding
import com.lancoo.znbkxx.teacher.model.data.GrammarInfo
import com.lancoo.znbkxx.teacher.model.data.LanguageInfo
import com.lancoo.znbkxx.teacher.model.data.PaperBaseInfo
import com.lancoo.znbkxx.teacher.model.data.ValidStu
import com.lancoo.znbkxx.teacher.ui.activity.HomeWorkActivity
import com.lancoo.znbkxx.teacher.ui.activity.OneonOneActivity
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.utils.MkUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.widget.AnalysisPopupWindow
import com.lancoo.znbkxx.teacher.widget.SwitchStudentWindow

import kotlinx.android.synthetic.main.item_stuname.view.*
import kotlinx.android.synthetic.main.popupwindow_stuname.view.iv_close
import kotlinx.android.synthetic.main.view_switch_student.view.*

/**s
 * @author : wealive
 * @date   : 2020/9/29 14:44
 * @desc   :
 */
class OnlineTutorFragment : BaseVMFragment<PaperViewModel, FmtOnlinetutorBinding>(),
        View.OnClickListener, BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemChildClickListener {
    private var position = 0
    private val validStuList = mutableListOf<ValidStu>()
    private lateinit var stuPopupWindow: SwitchStudentWindow
    private lateinit var analysisPopupWindow: AnalysisPopupWindow
    private lateinit var homeWorkAdapter: HomeWorkAdapter
    private val homeList = mutableListOf<PaperBaseInfo>()
    override fun providerVMClass(): Class<PaperViewModel> {
        return PaperViewModel::class.java
    }

    override fun providerContext(): Any? {
        return this
    }

    override fun setLayoutID(): Int {
        return R.layout.fmt_onlinetutor
    }

    override fun initView() {
        binding.tvTitle.typeface = Typeface.createFromAsset(requireContext().assets,
                "fonts/cool_black.TTF")
        binding.tvStuName.setOnClickListener(this)
        binding.ivSwitch.setOnClickListener(this)
        binding.tvMore.setOnClickListener(this)
        binding.ivDetail.setOnClickListener(this)
        homeWorkAdapter = HomeWorkAdapter(homeList)
        val emptyView = layoutInflater.inflate(R.layout.item_empty, null)
        homeWorkAdapter.emptyView = emptyView
        homeWorkAdapter.onItemChildClickListener = this
        val manager = LinearLayoutManager(activity)
        val map = hashMapOf<String, Int>()
        map[SpacesItemDecoration.TOP_SPACE] = DensityUtils.dp2px(requireContext(), 10f)
        val itemDecoration = SpacesItemDecoration(map)
        binding.rvHomework.addItemDecoration(itemDecoration)
        binding.rvHomework.layoutManager = manager
        binding.rvHomework.adapter = homeWorkAdapter
    }

    private fun initViewPager(grammarInfo: ArrayList<GrammarInfo>,
                              languageInfo: ArrayList<LanguageInfo>) {
        binding.vp.adapter = object : FragmentStateAdapter(childFragmentManager, lifecycle) {
            override fun getItemCount(): Int {
                return 2
            }

            override fun createFragment(position: Int): Fragment {
                return HomeWorkFragment().apply {
                    arguments = Bundle().apply {
                        putString("stuID", STU_ID)
                        putInt("layer", position)
                        if (position == 0) {
                            putParcelableArrayList("grammar", grammarInfo)
                        } else {
                            putParcelableArrayList("language", languageInfo)
                        }
                    }
                }
            }
        }
        binding.vp.isUserInputEnabled = false
        TabLayoutMediator(binding.tblPaper, binding.vp) { tab, position ->
            tab.text = when (position) {
                0 -> "语法知识辅导"
                else -> "语言能力辅导"
            }
        }.attach()
    }

    private fun getTeacherInfo() {
        (activity as OneonOneActivity).loadingDialog.show()
        viewModel.getTeacherInfo(CurrentUser.Token, CurrentUser.UserID)
    }

    private fun getRZInfo() {
        viewModel.getStuRZInfo(CurrentUser.Token, CurrentUser.UserID, STU_ID, SCHOOLID)
    }

    private fun previewStuHomeworkInfo() {
        viewModel.previewStuHomeworkInfo(CurrentUser.Token, CurrentUser.UserID, STU_ID,
                CurrentUser.SchoolID, -1)
    }

    private fun getHomeWorkList(layer: Int, state: Int, pageSize: Int) {
        viewModel.getPaperBaseInfoList(CurrentUser.Token, CurrentUser.UserID, STU_ID,
                CurrentUser.SchoolID, layer, 1, pageSize, state)
    }

    @SuppressLint("SetTextI18n")
    override fun startObserve() {
        viewModel.mTeacherInfo.observe(this, Observer {
            validStuList.clear()
            validStuList.addAll(it.ValidStuList)
            if (STU_ID.isEmpty()) {
                STU_ID = validStuList[0].StuID?:""
                MkUtils.encode("STU_ID", Ext.STU_ID)

                STU_NAME = validStuList[0].StuName
                MkUtils.encode("STU_NAME", Ext.STU_NAME)

                SCHOOLID = validStuList[0].SchoolID
                MkUtils.encode("SCHOOLID", Ext.STU_NAME)

                COURSE_CLASSID = validStuList[0].CourseClassID
                MkUtils.encode("COURSE_CLASSID",COURSE_CLASSID)
                GLOBAL_GRADE_STU = validStuList[0].GlobalGrade
                MkUtils.encode("GLOBAL_GRADE_STU", GLOBAL_GRADE_STU)
                validStuList[0].Checked = true
            } else {
                validStuList.forEach { stu ->
                    if (stu.StuID == STU_ID) stu.Checked = true
                }
            }
            getRZInfo()
            previewStuHomeworkInfo()
            getHomeWorkList(-1, 1, 3)
            stuPopupWindow = SwitchStudentWindow(requireContext(), validStuList)
            stuPopupWindow.contentView.tv_confirm.setOnClickListener(this)
            stuPopupWindow.contentView.iv_close.setOnClickListener(this)
            stuPopupWindow.setOnDismissListener {
                val lp = requireActivity().window.attributes
                lp.alpha = 1.0f
                requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                requireActivity().window.attributes = lp
            }
            binding.tvStuName.text = STU_NAME
            binding.tvStuHomework.text = "${STU_NAME}的作业情况"
        })
        viewModel.mRZInfo.observe(this, Observer {
            binding.tvTotalscore.text = it.ComprehensiveScore
            binding.tvTotalscoreUp.text = "${it.ComprehensiveScoreChange}↑"
            binding.tvIntegral.text = it.CognitiveScore
            binding.tvIntegralUp.text = "${it.CognitiveScoreChange}↑"
            binding.tvWords.text = it.Vocabulary
            binding.tvWordsUp.text = "${it.VocabularyChange}↑"
            binding.tvGrammar.text = it.GrammarScore
            binding.tvGrammarUp.text = "${it.GrammarScoreChange}↑"
            binding.tvLanguage.text = it.LanguageScore
            binding.tvLanguageUp.text = "${it.LanguageScoreChange}↑"
            initViewPager(it.GrammarInfo, it.LanguageInfo)
        })
        viewModel.mPreviewStuHomeworkInfo.observe(this, Observer {
            binding.tvAnswered.text = "${it.AnsweredPaperNum}份"
            binding.tvPublished.text = "${it.PublishedPaperNum}份"
            binding.tvCorrect.text = "${it.AverageAnswerRate}%"
        })
        viewModel.mPaperBaseInfoList.observe(this, Observer {
            (activity as OneonOneActivity).loadingDialog.dismiss()
            homeList.clear()
            homeList.addAll(it.List)
            homeWorkAdapter.setNewData(homeList)
        })
        viewModel.mHomeWorkAnalysis.observe(this, Observer {
//            val data = "[{\"PaperID\":\"620000198412281243\",\"PaperName\":\"课后作业1\",\"HVAL\":0.5,\"ScoringRate\":80},{\"PaperID\":\"220000199102211135\",\"PaperName\":\"课后作业2\",\"HVAL\":0.4,\"ScoringRate\":10}]"
//            val list = Gson().fromJson<MutableList<HomeWorkAnalysis>>(data,
//                    object : TypeToken<MutableList<HomeWorkAnalysis>>() {}.type)
            analysisPopupWindow = AnalysisPopupWindow(requireContext(), it)
            analysisPopupWindow.setOnDismissListener {
                val lp = requireActivity().window.attributes
                lp.alpha = 1.0f
                requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                requireActivity().window.attributes = lp
            }
            analysisPopupWindow.showAtLocation(binding.tvStuName, Gravity.BOTTOM, 0, 0)
            val lp = requireActivity().window.attributes
            lp.alpha = 0.8f
            requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            requireActivity().window.attributes = lp
        })
        viewModel.mHastenCall.observe(this, Observer {
            when (it) {
                0 -> MyToast.showToast( "催交作业成功")
                1 -> MyToast.showToast( "催交作业失败")
                else -> getHomeWorkList(-1, 1, 3)
            }
        })
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (adapter) {
            is StuNameAdapter -> {
                this.position = position
                adapter.data.forEach {
                    it.Checked = false
                }
                view?.tv_name?.isChecked = true
                adapter.data[position].Checked = true
                adapter.notifyDataSetChanged()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_stuName, R.id.iv_switch -> {
                stuPopupWindow.showAtLocation(binding.tvStuName, Gravity.BOTTOM, 0, 0)
                val lp = requireActivity().window.attributes
                lp.alpha = 0.8f
                requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                requireActivity().window.attributes = lp
            }
            R.id.iv_detail -> viewModel.getHomeworkStatisticAnalysis(CurrentUser.Token,
                    CurrentUser.UserID, STU_ID, SCHOOLID)
            R.id.tv_more -> {
                val intent = Intent(requireContext(), HomeWorkActivity::class.java)
                intent.putExtra("stuName", STU_NAME)
                intent.putExtra("stuID", STU_ID)
                startActivity(intent)
            }
            R.id.iv_close -> stuPopupWindow.dismiss()
            R.id.tv_confirm -> {
                stuPopupWindow.dismiss()
                STU_ID = stuPopupWindow.data.find { it.Checked }!!.StuID?:""
                MkUtils.encode("STU_ID", Ext.STU_ID)

                STU_NAME = stuPopupWindow.data.find { it.Checked }!!.StuName
                COURSE_CLASSID = stuPopupWindow.data.find { it.Checked }!!.CourseClassID
                MkUtils.encode("COURSE_CLASSID",COURSE_CLASSID)
                GLOBAL_GRADE_STU = stuPopupWindow.data.find { it.Checked }!!.GlobalGrade
                MkUtils.encode("GLOBAL_GRADE_STU", GLOBAL_GRADE_STU)
                binding.tvStuName.text = stuPopupWindow.data.find { it.Checked }!!.StuName
                binding.tvStuHomework.text = "${stuPopupWindow.data.find { it.Checked }!!.StuName}的作业情况"
                getRZInfo()
                previewStuHomeworkInfo()
                getHomeWorkList(-1, 1, 3)
            }
        }
    }


    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val homeWork = adapter!!.data[position] as PaperBaseInfo
        when (view?.id) {
            R.id.iv_hastencall -> viewModel.doHastenCallOneOnOne(CurrentUser.Token,
                    CurrentUser.UserID,
                    STU_ID, homeWork.PaperID, SCHOOLID)
            R.id.card -> {
                AibkPaperPreviewActivity.launch(requireActivity(), homeWork.PaperID, "",true)
            }
            R.id.tv_comment -> {
                AibkQuesMarkActivity.launch(requireActivity(), "setId", STU_ID, homeWork.PaperID,
                        homeWork.PaperName, true)
            }
            R.id.tv_detail -> {
                AibkAnalysisAnswerSheetActivity_1v1.launch(requireActivity(), STU_ID,
                        homeWork.PaperID, homeWork.PaperName)
            }
            R.id.iv_publish -> {
                MyToast.showToast("此处需要调用发布接口，添加一对一发布功能")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        getTeacherInfo()
    }
}